﻿using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace CzfSDK
{
	public static class ThreadTool
	{
		static bool Debug = true;
		// 所有线程
		private static Dictionary<int, StackTrace> _allThreadStackTrace = new Dictionary<int, StackTrace>();
		private static Dictionary<int, DateTime> _allThreadLastTime = new Dictionary<int, DateTime>();
		private static object _allThreadLock = new object ();

		public static Task TaskRun(Action action, TaskCreationOptions opt = TaskCreationOptions.None)
		{
			var task = new Task (() => {
				try {
					LogThread ();
					action();
				} catch (Exception e) {
					CzfLog.Error("TaskRun", e);
				}
			}, opt);
			task.Start ();
			return task;
		}

		public static void TaskDelay(int sleep)
		{
			Task.Delay (sleep).Wait ();
			LogThread ();
		}

		public static void LogThread()
		{
			if(Debug){
				lock(_allThreadLock){						
					_allThreadStackTrace[Thread.CurrentThread.ManagedThreadId] = new StackTrace(true);
					_allThreadLastTime[Thread.CurrentThread.ManagedThreadId] = DateTime.Now;
				}
			}
		}

		/// <summary>
		/// 查找当前所有正在运行的线程的堆栈信息
		/// </summary>
		/// <param name="pro">Pro.</param>
		public static void CheckLoop(Action<string> debug)
		{
			if (!Debug)
				debug ("开关未开启");

			lock (_allThreadLock) {
				debug ("线程数:" + _allThreadStackTrace.Count);
				foreach(var k in _allThreadStackTrace.Keys) {
					try {
						if (_allThreadStackTrace [k] != null) {
							debug ("线程ID:" + k);
							debug ("线程最后运行时间:" + _allThreadLastTime[k]);
							debug ("线程状态:" + _allThreadStackTrace [k].ToString());
						}
					} catch (Exception e) {
						debug ("出错:"+e.ToString ());
					}
				}
			}
		}
	}
}

